﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Mail;
using MINERP.BLL.GoodsDelivery;
using MINERP.COM;
using MINERP.MODEL.GoodsDelivery;

namespace ERPGoodsDelivery.Delivery
{
    public partial class FrmDeliverFind : Form
    {
        //参数
        private DeliverFindBLL bll = new DeliverFindBLL();
        private DeliverBackBLL backBll = new DeliverBackBLL();
        //属性
        private static FrmDeliverFind _instance;

        public static FrmDeliverFind GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new FrmDeliverFind();
                }
                return _instance;
            }
            set
            {
                _instance = value;
            }
        }
        //int 
        int CurrentShopId = 0;
        List<ShopNormal> _ShopList = new List<ShopNormal>();


        public FrmDeliverFind()
        {
            InitializeComponent();
        }

        private void FrmDeliverFind_Load(object sender, EventArgs e)
        {
            dtStartTime.DateTime = DateTime.Now.AddDays(-7).Date;
            dtEnd.DateTime = DateTime.Now.Date;
            //cbDeliveryStatus.Text = "全部";
            ;
            cbDeliveryStatus.SelectedIndex = 3;
            BindShop();
            gvBillInfoHeap.ShowFindPanel();
        }


        //查询
        private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                int shopId = Convert.ToInt32(cbShopList.SelectedValue);
                CurrentShopId = shopId;
                DateTime startTime = new DateTime(1900, 1, 1).Date;
                DateTime endTime = DateTime.Now.Date;
                if (!cbDisableStartTime.Checked)                    //启用时间范围
                {
                    startTime = dtStartTime.DateTime.Date;
                    endTime = dtEnd.DateTime.AddDays(1).Date;
                    if (endTime < startTime)
                    {
                        Cursor = Cursors.Default;
                        return;
                    }
                }
                string ctmName = txtCtmName.Text.Trim();
                string orderProductCode = txtOrderProductCode.Text.Trim();
                if (orderProductCode.Length > 0)
                {
                    if (orderProductCode.Length > 10)
                    {
                        MessageBox.Show("产品编号最多为10位！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtOrderProductCode.Focus();
                        txtOrderProductCode.SelectAll();
                        Cursor = Cursors.Default;
                        return;
                    }
                    else if (orderProductCode.Length < 10)
                    {
                        int code = 0;
                        try
                        {
                            code = Convert.ToInt32(txtOrderProductCode.Text.Trim());
                        }
                        catch
                        {
                            MessageBox.Show("请输入正确的产品编号！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            txtOrderProductCode.Focus();
                            txtOrderProductCode.SelectAll();
                            Cursor = Cursors.Default;
                            return;
                        }
                        orderProductCode = "2" + string.Format("{0:d9}", code);
                    }
                }
                int status = -1;                //-1表示所有状态的发货单
                switch (cbDeliveryStatus.Text.Trim())
                {
                    case "全部":
                        status = -1; break;
                    case "等待发货":
                        status = (int)DeliveryStatus.NoPrint; break;
                    case "正在发货":
                        status = (int)DeliveryStatus.Printed; break;
                    case "已发货":
                        status = (int)DeliveryStatus.Deliverred; break;
                }
                List<DeliveryBack> bills = null;
                if (shopId != 0)
                {
                    bills = bll.GetDeliveryBillByShopId(shopId, startTime, endTime, ctmName, orderProductCode, status);
                }
                else
                {
                    bills = bll.GetDeliveryBillByShopId(startTime, endTime, ctmName, orderProductCode, status);
                }
                gcBillInfoHeap.DataSource = bills;
                gcBillInfoHeap.RefreshDataSource();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //单击显示产品
        private void gvBillInfoHeap_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            try
            {
                int billId = Convert.ToInt32(gvBillInfoHeap.GetRowCellValue(e.RowHandle, "BillId"));
                BindOrderInfo(billId);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //焦点变化显示产品
        private void gvBillInfoHeap_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (e.FocusedRowHandle >= 0)
                {
                    int billId = Convert.ToInt32(gvBillInfoHeap.GetRowCellValue(e.FocusedRowHandle, "BillId"));
                    BindOrderInfo(billId);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //导出
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvOrderProductInfo.DataSource != null)
                {
                    List<DeliverFindBLL.OrderInfoCL> orderInfos = gvOrderProductInfo.DataSource as List<DeliverFindBLL.OrderInfoCL>;
                    FastReport.Report report = new FastReport.Report();
                    //头信息
                    DeliveryBack back = gvBillInfoHeap.GetRow(gvBillInfoHeap.GetSelectedRows()[0]) as DeliveryBack;
                    DataTable deliverTitle = backBll.CreateDeliverBillInfo();
                    DataRow nr = deliverTitle.NewRow();
                    nr["ArrivalTime"] = back.ArrivalTime;
                    nr["BillId"] = back.BillId;
                    nr["BillIndexId"] = back.BillOrderCode;    //这里要注意
                    nr["DeliverId"] = back.DeliverId;
                    nr["DeliverObject"] = back.DeliverObject;
                    nr["DeliverTime"] = back.DeliverTime;
                    nr["Num"] = back.Num;
                    nr["OtherMoney"] = back.OtherMoney;
                    nr["ReceiveStationRemark"] = back.ReceiveStationRemark;
                    nr["SelfMoney"] = back.SelfMoney;
                    nr["ShopMoney"] = back.ShopMoney;
                    nr["StationRemark"] = back.StationRemark;
                    nr["TuoYunDanCode"] = back.TuoYunDanCode;
                    deliverTitle.Rows.Add(nr);
                    deliverTitle.TableName = "deliverTitle";

                    DataTable dt = bll.CreateOutDt();
                    foreach (DeliverFindBLL.OrderInfoCL info in orderInfos)
                    {
                        DataRow nrr = dt.NewRow();
                        nrr["CtmName"] = info.CtmName;
                        nrr["OrderProductCode"] = info.OrderProductCode;
                        nrr["OrderProductName"] = info.OrderProductName;
                        dt.Rows.Add(nrr);
                    }
                    dt.TableName = "deliverOrderInfo";
                    DataSet ds = new DataSet();
                    ds.Tables.Add(deliverTitle);
                    ds.Tables.Add(dt);
                    ds.WriteXml(@"C:\WINDOWS\xmlData\deliverOrderInfos.xml", XmlWriteMode.WriteSchema);
                    report.Load(Application.StartupPath + "\\deliverOrderInfo.frx");

                    //导出路径
                    string savePath = "";
                    saveFileDialog1.RestoreDirectory = true;
                    if (DialogResult.OK == saveFileDialog1.ShowDialog())
                    {
                        savePath = saveFileDialog1.FileName;
                    }
                    else
                    {
                        return;
                    }
                    report.Prepare();

                    FastReport.Export.Xml.XMLExport export = new FastReport.Export.Xml.XMLExport();
                    export.AllowOpenAfter = false;
                    export.Export(report, savePath);
                    MessageBox.Show("导出成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    report.Dispose();
                    //report.RegisterData(dt, "deliverOrderInfo");
                    //report.Show();
                }
                else
                {
                    MessageBox.Show("没有数据存在！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                return;

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|pdf(*.pdf)|*.pdf|电子表格(*.xls)|*.xls|html(*.html)|*.html";
                //saveFileDialog.AddExtension = true;
                saveFileDialog.FilterIndex = 3;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.OverwritePrompt = true;

                gvOrderProductInfo.OptionsPrint.PrintDetails = true;
                this.gvOrderProductInfo.OptionsPrint.ExpandAllDetails = true;
                this.gvOrderProductInfo.OptionsPrint.ExpandAllGroups = true;
                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string fileName = saveFileDialog.FileName;
                    if (saveFileDialog.OpenFile() != null)
                    {
                        switch (saveFileDialog.FilterIndex)
                        {
                            case 3:
                                gvOrderProductInfo.ExportToXls(fileName);
                                return;
                            case 4:
                                gvOrderProductInfo.ExportToHtml(fileName);
                                return;
                            case 2:
                                gvOrderProductInfo.ExportToPdf(fileName);
                                return;
                            case 1:
                                this.gvOrderProductInfo.ExportToText(fileName);
                                return;
                            default:
                                break;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //自动发信设置
        private void tsEmailSet_Click(object sender, EventArgs e)
        {
            try
            {
                FrmEmailSet frm = FrmEmailSet.GetInstance;
                frm.CurrentShopId = CurrentShopId;
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //自动发邮件
        private void tsSendMail_Click(object sender, EventArgs e)
        {
            try
            {
                AutoSendMail();
            }
            catch (Exception)
            {
                MessageBox.Show("未能正确设置邮箱信息！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //是否启用时间范围
        private void cbDisableStartTime_CheckedChanged(object sender, EventArgs e)
        {
            if (cbDisableStartTime.Checked)
            {
                dtStartTime.Enabled = false;
            }
            else
            {
                dtStartTime.Enabled = true;
            }
        }

        //是否启用时间范围
        private void cbDeliveryStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbDeliveryStatus.Text == "全部" || cbDeliveryStatus.Text == "已发货")
            {
                dtStartTime.Enabled = true;
                dtEnd.Enabled = true;
            }
            else
            {
                dtStartTime.Enabled = false;
                dtEnd.Enabled = false;
            }
        }

        //----------------------------------------------------------------------
        //----------------------------公共方法----------------------------------
        //----------------------------------------------------------------------
        private void BindShop()
        {
            try
            {
                List<ShopNormal> shops = bll.GetShopList();
                //排序
                _ShopList=shops = shops.OrderBy(p => p.ShopName).ToList();
                ShopNormal s = new ShopNormal();
                s.ShopId = 0;
                s.ShopName = "全选";
                shops.Insert(0, s);
                cbShopList.DisplayMember = "ShopName";
                cbShopList.ValueMember = "ShopId";
                cbShopList.DataSource = shops;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void BindShop(string inChar)
        {
            try
            {
                List<ShopNormal> shops =string.IsNullOrEmpty(inChar)?_ShopList:_ShopList.Where(s => s.mnemonicCode.ToUpper().Contains(inChar.ToUpper())).ToList();
                //排序
             
                ShopNormal ss = new ShopNormal();
                ss.ShopId = 0;
                ss.ShopName = "全选";
                shops.Insert(0, ss);
                cbShopList.DisplayMember = "ShopName";
                cbShopList.ValueMember = "ShopId";
                cbShopList.DataSource = shops;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void BindOrderInfo(int billId)
        {
            try
            {
                List<DeliverFindBLL.OrderInfoCL> infos = bll.GetOrderProductByBillId(billId);
                gcOrderProductInfo.DataSource = infos;
                gcOrderProductInfo.RefreshDataSource();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 自动发邮件
        /// </summary>
        private void AutoSendMail()
        {
            try
            {
                if (gvOrderProductInfo.DataSource != null)
                {
                    //邮件报表
                    List<DeliverFindBLL.OrderInfoCL> orderInfos = gvOrderProductInfo.DataSource as List<DeliverFindBLL.OrderInfoCL>;
                    FastReport.Report report = new FastReport.Report();
                    //头信息
                    DeliveryBack back = gvBillInfoHeap.GetRow(gvBillInfoHeap.GetSelectedRows()[0]) as DeliveryBack;
                    DataTable deliverTitle = backBll.CreateDeliverBillInfo();
                    DataRow nr = deliverTitle.NewRow();
                    int shopId = back.ShopId;
                    nr["ArrivalTime"] = back.ArrivalTime;
                    nr["BillId"] = back.BillId;
                    nr["BillIndexId"] = back.BillOrderCode;    //这里要注意
                    nr["DeliverId"] = back.DeliverId;
                    nr["DeliverObject"] = back.DeliverObject;
                    nr["DeliverTime"] = back.DeliverTime;
                    nr["Num"] = back.Num;
                    nr["OtherMoney"] = back.OtherMoney;
                    nr["ReceiveStationRemark"] = back.ReceiveStationRemark;
                    nr["SelfMoney"] = back.SelfMoney;
                    nr["ShopMoney"] = back.ShopMoney;
                    nr["StationRemark"] = back.StationRemark;
                    nr["TuoYunDanCode"] = back.TuoYunDanCode;
                    deliverTitle.Rows.Add(nr);
                    deliverTitle.TableName = "deliverTitle";

                    DataTable dt = bll.CreateOutDt();
                    foreach (DeliverFindBLL.OrderInfoCL info in orderInfos)
                    {
                        DataRow nrr = dt.NewRow();
                        nrr["CtmName"] = info.CtmName;
                        nrr["OrderProductCode"] = info.OrderProductCode;
                        nrr["OrderProductName"] = info.OrderProductName;
                        dt.Rows.Add(nrr);
                    }
                    dt.TableName = "deliverOrderInfo";
                    DataSet ds = new DataSet();
                    ds.Tables.Add(deliverTitle);
                    ds.Tables.Add(dt);
                    ds.WriteXml(@"C:\WINDOWS\xmlData\deliverOrderInfos.xml", XmlWriteMode.WriteSchema);
                    report.Load(Application.StartupPath + "\\deliverOrderInfo.frx");
                    //report.RegisterData(dt, "deliverOrderInfo");
                    report.Prepare();
                    //FastReport.Export.Xml.XMLExport export = new FastReport.Export.Xml.XMLExport();
                    FastReport.Export.Html.HTMLExport export = new FastReport.Export.Html.HTMLExport();
                    export.SinglePage = true;
                    export.Navigator = true;
                    export.Wysiwyg = true;
                    export.Pictures = true;
                    export.SubFolder = true;
                    export.AllowOpenAfter = false;
                    report.Export(export, @"C:\WINDOWS\xmlData\deliverTemp.html");                   //导出临时邮件文件
                    //发送
                    string shopMailAddr = bll.GetShopMailAddr(shopId);
                    string sendMailAddr = Properties.Settings.Default.userSendBoxAddress;
                    string smtpServer = Properties.Settings.Default.userSmtpServer;
                    string pwd = Properties.Settings.Default.userPwd;
                    string title = Properties.Settings.Default.userTitle;
                    string content = Properties.Settings.Default.userContent;
                    string userName = Properties.Settings.Default.UserName;
                    string attachMent = @"C:\WINDOWS\xmlData\deliverTemp.files\deliverTemp.main.html";                      //附件

                    string[] sends = sendMailAddr.Split('@');
                    SmtpClient client = new SmtpClient(smtpServer);
                    client.UseDefaultCredentials = false;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.Credentials = new NetworkCredential(userName, pwd);
                    MailMessage mmsg = new MailMessage(sendMailAddr, shopMailAddr);
                    mmsg.Subject = title;
                    mmsg.SubjectEncoding = Encoding.UTF8;
                    mmsg.Body = content;
                    mmsg.BodyEncoding = Encoding.UTF8;
                    mmsg.IsBodyHtml = true;
                    mmsg.Priority = MailPriority.High;
                    mmsg.Attachments.Add(new Attachment(attachMent));
                    try
                    {
                        client.Send(mmsg);
                        MessageBox.Show("邮件发送成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    mmsg.Dispose();
                    report.Dispose();
                    //删除临时邮件
                    //if (File.Exists(@"C:\WINDOWS\xmlData\deliverTemp.xls"))
                    //{
                    //    File.Delete(@"C:\WINDOWS\xmlData\deliverTemp.xls");
                    //}
                }
                else
                {
                    MessageBox.Show("没有数据存在！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            BindShop(textBox1.Text);
        }

    }
}
